package com.ruoyi.web.controller.customer;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageHelper;
import com.ruoyi.api.domain.AppManage;
import com.ruoyi.api.domain.Device;
import com.ruoyi.api.domain.RecRecord;

import com.ruoyi.api.service.IAppManageService;
import com.ruoyi.api.service.IDeviceService;
import com.ruoyi.api.service.IRecRecordService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.Phenologicalperiods;
import com.ruoyi.system.domain.vo.PhenologicalperiodsVo;
import com.ruoyi.system.service.IPhenologicalperiodsService;

/**
 * 首页数据展示Controller
 * 
 * @author ruoyi
 * @date 2025-05-22
 */
@RestController
@RequestMapping("/customer/dashboard")
public class CustomerDashboardController extends BaseController {
    
    @Autowired
    private IAppManageService appManageService;
    
    @Autowired
    private IDeviceService deviceService;
    
    @Autowired
    private IRecRecordService recRecordService;
    
    @Autowired
    private IPhenologicalperiodsService phenologicalperiodsService;
    

    
    /**
     * 获取首页统计数据
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/stats")
    public AjaxResult getStats() {
        Map<String, Object> statsMap = new HashMap<>();
        
        // 获取当前用户的应用统计
        AppManage appQuery = new AppManage();
        appQuery.setCreateBy(getUsername());
        List<AppManage> appList = appManageService.selectAppManageList(appQuery);
        
        // 获取当前用户的设备统计
        Device deviceQuery = new Device();
        deviceQuery.setCreateBy(getUsername());
        List<Device> deviceList = deviceService.selectDeviceList(deviceQuery);
        
        // 应用统计
        Map<String, Object> appStats = new HashMap<>();
        appStats.put("total", appList.size());
        
        // 按应用状态分组统计
        Map<Object, Long> appStatusCount = appList.stream()
                .collect(Collectors.groupingBy(app -> app.getStatus() != null ? app.getStatus() : "未知", 
                        Collectors.counting()));
        appStats.put("statusDistribution", appStatusCount);
        
        // 按应用类型分组统计（手动、定时、全部）
        Map<Object, Long> appTypeCount = appList.stream()
                .collect(Collectors.groupingBy(app -> app.getAppType() != null ? app.getAppType() : "未知", 
                        Collectors.counting()));
        appStats.put("typeDistribution", appTypeCount);
        

        
        // 设备统计
        Map<String, Object> deviceStats = new HashMap<>();
        deviceStats.put("total", deviceList.size());
        
        // 按设备状态分组统计
        Map<Object, Long> deviceStatusCount = deviceList.stream()
                .collect(Collectors.groupingBy(device -> device.getStatus() != null ? device.getStatus() : "未知", 
                        Collectors.counting()));
        deviceStats.put("statusDistribution", deviceStatusCount);
        
        // 添加到返回结果
        statsMap.put("appStats", appStats);
        statsMap.put("deviceStats", deviceStats);
        
        return success(statsMap);
    }
    
    /**
     * 获取物候期数据
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/phenology")
    public AjaxResult getPhenologyData() {
        // 查询当前用户的物候期数据
        Phenologicalperiods query = new Phenologicalperiods();
        query.setCreateBy(getUsername()); // 设置为当前登录用户
        List<PhenologicalperiodsVo> phenologyList = phenologicalperiodsService.selectPhenologicalperiodsListVo(query);
        
        // 按作物分组统计物候期数量
        Map<Object, Long> cropPhenologyCount = phenologyList.stream()
                .collect(Collectors.groupingBy(p -> p.getCropName() != null ? p.getCropName() : "未知", 
                        Collectors.counting()));
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalPhenology", phenologyList.size());
        result.put("cropDistribution", cropPhenologyCount);
        result.put("phenologyList", phenologyList);
        
        return success(result);
    }
    
    /**
     * 获取最新预警记录
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/latestWarnings")
    public TableDataInfo getLatestWarnings() {
        // 查询当前用户的预警记录
        RecRecord recRecord = new RecRecord();
        recRecord.setCreateBy(getUsername());
        recRecord.setDanger(1); // 只查询预警记录
        
        // 设置按创建时间降序排序，最新的记录排在前面
        startPage();
        PageHelper.orderBy("create_time desc");
        List<RecRecord> list = recRecordService.selectRecRecordList(recRecord);
        
        return getDataTable(list);
    }
}